import editCommon from "./editCommon";

var designModelMap = {};
var variablePool = editCommon.variablePool;
editCommon.prototypeDefine();


var editSvgCore = {
    initSvg: initSvg,
    getSvgInfoJson: getSvgInfoJson,
    // getSvgBase64Image: getSvgBase64Image,
    //所有可编辑对象点击的回调
    svgEditCallback: function() {

    },
    //所有区域点击对象点击的回调
    svgAreaAllCallback: function() {

    },
    //删除所有可编辑对象点击的回调
    removeSvgObjCallback: function(name, type) {

    },
    //点击文字对象的回调
    svgTextEditCallback: function() {

    },
    //取消选中文字对象的回调
    cancelSvgTextEditCallback: function() {

    },
    //点击用户图片对象的回调
    svgUserImageEditCallback: function() {

    },
    //取消选中用户图片对象的回调
    cancelSvgUserImageEditCallback: function() {

    },
    //点击素材图片对象的回调
    svgMaterialEditCallback: function() {

    },
    //取消选中素材图片对象的回调
    cancelSvgMaterialEditCallback: function() {

    },
    //获取userImage
    // getUserSvgImage: getUserSvgImage,
    //添加userImage
    addUserSvgImage: addUserSvgImage,
    //添加素材
    addMaterialToSvg: addMaterialToSvg,
    //点击Mask层
    touchMaskCallback: function() {

    }
};

function loadSvgImageByBase64(options) {
    var svgObj = editSvgCore.svgObj,
        svg = svgObj.svg;
    var params = options.params,
        data = options.data,
        target = options.target,
        imageUrl = params.imageUrl,
        callback = options.callback,
        imageObj = options.imageObj,
        width = params.width,
        height = params.height,
        x = params.x,
        y = params.y,
        isExsists = false;
    editCommon.convertImgToBase64(params.imageUrl, function(base64Img) {
        // var base64Img=params.imageUrl;
        data.imagebase64 = base64Img;
        var svg_tmp_image = imageObj;
        if (svg_tmp_image) {
            svg_tmp_image.load(base64Img);
            // refreshComponent(svg_tmp_image,svgObj.selectGroup);
            isExsists = true;
        } else {
            svg_tmp_image = svg.image(base64Img, width, height);
        }
        // svg_tmp_image.data("href",realImageUrl);
        if (!isExsists) {
            target.add(svg_tmp_image);
            svg_tmp_image.data("name", "image");
            addOperateGroup(svg_tmp_image, "hide");
        }
        if (callback) {
            callback(svg_tmp_image);
        }
    })

}

function determinePintInArea(transformBox) {
    var svgObj = editSvgCore.svgObj;
    var printAreaObj = svgObj.printArea;
    if (!transformBox) {
        printAreaObj.attr({
            "stroke": "#8398d0"
        });
        return;
    }
    if (printAreaObj) {
        //判断点是否在区域内
        var tl_flag = printAreaObj.inside(transformBox.tl.x, transformBox.tl.y);
        var tr_flag = printAreaObj.inside(transformBox.tr.x, transformBox.tr.y);
        var bl_flag = printAreaObj.inside(transformBox.bl.x, transformBox.bl.y);
        var br_flag = printAreaObj.inside(transformBox.br.x, transformBox.br.y);
        if (tl_flag && tr_flag && bl_flag && br_flag) {
            printAreaObj.attr({
                "stroke": "#8398d0"
            });
        } else {
            printAreaObj.attr({
                "stroke": "#f00"
            });
        }
    }
}


function refreshComponent(target, group, textType) {

    var svgObj = editSvgCore.svgObj,
        _id = target.attr("id"),
        _name = target.data("name"),
        _type = target.data("type"),
        obj = null;
    if (_name == "image") {
        if (_type == "userImage") {
            obj = designModelMap.userImages;
        } else {
            obj = designModelMap.materials;
        }
    } else if (_name == "text") {
        obj = designModelMap.texts;
    }
    if (obj) { //重置所有属性  文字图片
        refreshImageTextProperties(target, obj, _name, textType);
    }
    var transform = target.transform();
    var bbox = target.bbox();
    var l = bbox.x,
        t = bbox.y,
        w = bbox.width,
        h = bbox.height,
        bbox = {
            x: l,
            y: t,
            width: w,
            height: h
        };
    var matrix = new SVG.Matrix(target);
    var transformBox = editCommon.transformBox(l, t, w, h, matrix);
    //判断是否超出可编辑区
    determinePintInArea(transformBox);
    var ratio_temp = variablePool.viewbox_ratio;
    var icon_width = 30 * ratio_temp;
    var gridObj = svgObj.gridObj;
    if (gridObj) {
        gridObj.attr({
            "stroke-width": 1 * ratio_temp,
            "stroke-dasharray": 8 * ratio_temp + "," + ratio_temp * 3
        });
    }
    if (group) {
        group.each(function(item) {
            var name = item.data("name");
            switch (name) {
                case "move":
                    item.attr({
                        "x": transformBox.tl.x - icon_width / 2,
                        "y": transformBox.tl.y - icon_width / 2,
                        width: icon_width,
                        height: icon_width,
                    });
                    break;
                case "scale":
                    item.attr({
                        "x": transformBox.tr.x - icon_width / 2,
                        "y": transformBox.tr.y - icon_width / 2,
                        width: icon_width,
                        height: icon_width,
                    });
                    break;
                case "rotate":
                    item.attr({
                        "x": transformBox.br.x - icon_width / 2,
                        "y": transformBox.br.y - icon_width / 2,
                        width: icon_width,
                        height: icon_width,
                    });
                    break;
                case "remove":
                    item.attr({
                        "x": transformBox.tl.x - icon_width / 2,
                        "y": transformBox.tl.y - icon_width / 2,
                        width: icon_width,
                        height: icon_width,
                    });
                    break;
                case "path":

                    item.plot('M ' + transformBox.tl.x + ' ' + transformBox.tl.y + ' L ' + transformBox.tr.x + ' ' + transformBox.tr.y + ' ' + transformBox.br.x + ' ' + transformBox.br.y + ' ' + transformBox.bl.x + ' ' + transformBox.bl.y + ' Z');
                    item.attr({
                        "stroke-width": 1,
                        "stroke-dasharray": "0", //8*ratio_temp+","+ratio_temp*3
                        "stroke": "#C0A369"
                    });
                    break;
                default:
                    break;
            }
        });
    }
}

function addUserSvgImage(item, callback) {
    var svgObj = editSvgCore.svgObj,
        svg = svgObj.svg,
        userImage_g = svgObj.userImage_g,
        userImages = svgObj.userImages;
    var width = item.width,
        height = item.height,
        imageUrl = item.imagePath;
    var userImageData = {
        width: width,
        height: height,
        url: imageUrl,
    };
    loadSvgImageByBase64({
        params: {
            width: width,
            height: height,
            imagebase64: item.imagebase64,
            imageUrl: imageUrl
        },
        imageObj: userImages,
        data: userImageData,
        target: userImage_g,
        callback: function(target) {
            target.data("type", "userImage");
            var id = target.attr("id");
            // var bbox=target.bbox();
            // item.imgDpi=item.imgDpi||200;

            //重新设置图片高宽
            target.attr({
                "width": width,
                "height": height
            });
            var maskImage = variablePool.maskImage;
            // var viewbox = svg.viewbox();
            var x = maskImage.width / 2 - width / 2 + parseFloat(maskImage.maskX),
                y = maskImage.height / 2 - height / 2 + parseFloat(maskImage.maskY);
            // var x=maskImage.maskX,y=maskImage.maskY;
            var scale = Math.min(maskImage.width / width, maskImage.height / height);
            var matrix = new SVG.Matrix;
            // matrix=matrix.scale(scale);
            matrix = matrix.translate(x, y);
            target.matrix(matrix);
            target.scale(scale);
            // target.translate(x,y);
            refreshComponent(target, svgObj.selectGroup);
            var transform = target.transform();
            userImageData.matrix = {
                "rotate": transform.rotation,
                "scale": transform.scaleX,
                "translateX": transform.x,
                "translateY": transform.y
            };
            userImageData.matrixString = new SVG.Matrix(target).toString();
            userImageData.realImageUrl = imageUrl;
            svgObj.userImages = target;
            designModelMap.userImages[id] = userImageData;
            if (callback) {
                callback();
            }
        }
    });
}

function getSvgInfoJson(callback) {
    return completeEditSvg(function(data) {
        if (callback) {
            callback({
                imageUrl: data.imageUrl,
                svgContentJson: data.svgContentJson
            });
        }
    });
}

function completeEditSvg(callback) {
    var svgObj = editSvgCore.svgObj,
        svg = svgObj.svg,
        canvas_g = svgObj.canvas_g,
        back_g = svgObj.back_g,
        bgmaterial_g = svgObj.bgmaterial_g,
        bgcolor_g = svgObj.bgcolor_g,
        face_g = svgObj.face_g,
        background_g = svgObj.background_g, //编辑区背景颜色
        userImage_g = svgObj.userImage_g,
        materials_g = svgObj.materials_g,
        texts_g = svgObj.texts_g,
        decorator_g = svgObj.decorator_g,
        mask_g = svgObj.mask;
    delete svgObj.maskuserImage_g;
    if (svgObj.operateG) {
        svgObj.operateG.forEach(function(item) {

            item.g.children().forEach(function(child) {
                child.hide();
            })
        });
    }
    var svgContentJson = {
        words: [],
        imgUri: [],
    };

    var back = designModelMap.back,
        materials = designModelMap.materials,
        backgroundImages = designModelMap.backgroundImages,
        texts = designModelMap.texts,
        userImages = designModelMap.userImages,
        maskImage = designModelMap.mask;
    var $svgTemp = $("<svg></svg>");
    $svgTemp.attr({
        // version:"1.1", 
        x: 0,
        y: 0,
        xmlns: "http://www.w3.org/2000/svg",
        "xmlns:xlink": "http://www.w3.org/1999/xlink",
        viewbox: "0 0 " + back.width + " " + back.height,
        style: "enable-background:new 0 0 " + back.width + " " + back.height,
        "xml:space": "preserve"
    });
    if ($("#svg_save_temp").length < 1) {
        $(document.body).append($("<div id='svg_save_temp' style='display:none'></div>"))
    }
    var svg_save_temp = SVG("svg_save_temp");

    var userImage_g_temp = userImage_g.clone();
    svg_save_temp.add(userImage_g_temp);
    var userImage_g_children_temp = userImage_g_temp.children();
    if (userImage_g_children_temp && userImage_g_children_temp.length > 0) {
        $.each(userImage_g_children_temp, function(index, item) { //编辑区用户图片层
            var id = item.attr("id");
            item.attr({
                    "style": "overflow:visible",
                    id: "userImg",
                    "href": null,
                    "data-link-href": item.data("href"),
                })
                // item.data("href",null);
                // var item_obj=userImages[id];
                // if(item_obj){ 
            for (var i in userImages) {
                var item_obj = userImages[i];
                svgContentJson.imgUri.push({
                    matrix: editCommon.revertMatrix(item_obj.matrixString),
                    height: item_obj.height,
                    maskX: item_obj.matrix.translateX,
                    maskY: item_obj.matrix.translateY,
                    width: item_obj.width,
                    isSuit: item_obj.isSuit || "N",
                    id: item_obj.id || "userImg",
                    imgFlag: item_obj.imgFlag || 1,
                    url: item_obj.url.lastIndexOf("?") > 0 ? editCommon.revertImageUrl(item_obj.url.substring(0, item_obj.url.lastIndexOf("?"))) : editCommon.revertImageUrl(item_obj.url),
                    locked: item_obj.locked || false,
                    page: item_obj.page || 1,
                    isMaterial: item_obj.isMaterial || 0,
                });
            }
            $(frame_g_temp.node).append(item.node.cloneNode(true));
        });
    }

    var materials_g_temp = materials_g.clone();
    svg_save_temp.add(materials_g_temp);
    var materials_g_children_temp = materials_g_temp.children();
    if (materials_g_children_temp && materials_g_children_temp.length > 0) {
        for (var i in materials) {
            var item_obj = materials[i];
            svgContentJson.imgUri.push({
                matrix: editCommon.revertMatrix(item_obj.matrixString),
                height: item_obj.isDefaultMaterial ? item_obj.height : item_obj.height / 2,
                maskX: item_obj.matrix.translateX,
                maskY: item_obj.matrix.translateY,
                width: item_obj.isDefaultMaterial ? item_obj.width : item_obj.width / 2,
                isSuit: item_obj.isSuit || "N",
                id: item_obj.id || "materialImg",
                imgFlag: item_obj.imgFlag || 2,
                url: editCommon.revertImageUrl(item_obj.url),
                locked: item_obj.locked || false,
                page: item_obj.page || 1,
                isMaterial: item_obj.isMaterial || 0,
            });
        }

        $.each(materials_g_children_temp, function(index, item) { //编辑区素材层
            var id = item.attr("id");
            item.attr({
                    "style": "overflow:visible",
                    id: "materialImg",
                    "href": null,
                    "data-link-href": item.data("href"),
                })
                // item.data("href",null);
            $(frame_g_temp.node).append(item.node.cloneNode(true));
        });
        // var item_obj=materials[id];
        // var len=materials?materials.length:0;

    }

    var texts_g_temp = texts_g.clone();
    svg_save_temp.add(texts_g_temp);
    var texts_g_children_temp = texts_g_temp.children();
    if (texts_g_children_temp && texts_g_children_temp.length > 0) {
        for (var i in texts) {
            var item_obj = texts[i];
            svgContentJson.words.push({
                matrix: editCommon.revertMatrix(item_obj.matrixString),
                maskX: item_obj.matrix.translateX,
                maskY: item_obj.matrix.translateY,
                typeface: item_obj.fontName,
                textContent: item_obj.text,
                fontSize: item_obj.fontSize,
                textColor: item_obj.textColor,
                fontWeight: item_obj.fontWeight,
                fontStyle: item_obj.fontStyle,
                dy: item_obj.dy,
                id: "",
            });
            // svgObj.selectGroup = null;
        }
        $.each(texts_g_children_temp, function(index, item) { //编辑区文字层
            item.attr({
                "style": "overflow:visible",
            })
            var id = item.attr("id");
            // var item_obj=userImages[id];
            // if(item_obj){

            $(frame_g_temp.node).append(item.node.cloneNode(true));
        });
    }

    $svgTemp.append(frame_g_temp.node.cloneNode(true));
    //装饰层处理
    var decorator_g_temp = decorator_g.clone();
    svg_save_temp.add(decorator_g_temp);
    decorator_g_temp.attr('pointer-events', null);
    var decorator_g_children_temp = decorator_g_temp.children();
    if (decorator_g_children_temp && decorator_g_children_temp.length > 0) {
        $.each(decorator_g_children_temp, function(index, item) { //背景层
            item.attr({
                    "style": "overflow:visible",
                    id: "d-1_xA0_",
                    "href": null,
                    "data-link-href": item.data("href"),
                })
                // item.data("href",null);
        });
        decorator_g_temp.attr({
            "id": "d-1_xA0__1_"
        });
        $svgTemp.append(decorator_g_temp.node.cloneNode(true));
    }
    // $(svgTemp).html(style+$(canvas_g.node).html());
    // $(svgTemp).html($(saveSvg.node).html());
    var $svgContent = $("<div></div>").append($svgTemp);
    var svgContent = $svgContent.html();
    // svgContent = svgContent.replace(/ns[\d]*:href/ig, "xlink:href").replace(/(matrix\s*\(\s*)(\d[\.]+),(\d+),(\d+),(\d+),(\d+),(\d+)/ig,function($0,$1,$2,$3,$4,$5,$6,$7){
    svgContent = svgContent.replace(/ns[\d]*:href/ig, "xlink:href").replace(/(matrix\s*\(\s*)(\-?\d*\.?\d+)\s*,\s*(\-?\d*\.?\d+)\s*,\s*(\-?\d*\.?\d+)\s*,\s*(\-?\d*\.?\d+)\s*,\s*(\-?\d*\.?\d+)\s*,\s*(\-?\d*\.?\d+)\s*/ig, function($0, $1, $2, $3, $4, $5, $6, $7) {
        return $1 + $2 + " " + $3 + " " + $4 + " " + $5 + " " + $6 + " " + $7
    }).replace(/(data-link-href)/ig, "xlink:href");
    // editCommon.log(svgContent);
    $("#svg_save_temp").remove();
    var svgTemp2 = svg.node.cloneNode(false);
    $(svgTemp2).removeAttr("x");
    $(svgTemp2).removeAttr("y");
    $(svgTemp2).removeAttr("version");
    $(svgTemp2).attr({
        xmlns: "http://www.w3.org/2000/svg",
        "xmlns:xlink": "http://www.w3.org/1999/xlink"
    });
    var backImage = variablePool.backImage;
    $(svgTemp2).attr({
        width: backImage.width / 2,
        height: backImage.height / 2
    });
    $(svgTemp2).html($(canvas_g.node).html());
    //    var $svg_background= $(svgTemp2).find("#svg_background");
    //    $svg_background.remove();
    var $svgContent2 = $("<div></div>").append($(svgTemp2));
    var svgContent2 = $svgContent2.html();
    svgContent2 = svgContent2.replace(/ns[\d]*:href/ig, "xlink:href");
    // editCommon.log(["svgContent2-------",svgContent2])
    // var base64xml="data:image/svg+xml;utf8,"+svgContent2;
    var base64xml = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgContent2)));
    // window.open(base64xml);
    // var canvas = document.createElement("canvas");
    // canvas.width = 1024;
    // canvas.height = 1024;
    // var ctx=canvas.getContext("2d");
    // var image
    // ctx.drawImage()

    editCommon.convertImgToBase64(base64xml, function(base64Img) {

        // window.open(base64Img);
        if (type != "imageUrl") {
            editCommon.putBase64ImgToAli(base64Img, function(res) {
                var thumbnailUrl = "";
                if (res.code == 200) {
                    thumbnailUrl = res.result;
                    // appJson.thumbilUrl=base64Img;//解决字体在3d模型上不显示 ？新问题中文乱码
                    // appJson.thumbilUrl = thumbnailUrl; //解决字体在3d模型上不显示 ？新问题中文乱码
                } else {
                    thumbnailUrl = "https://m.taidu.com/m3d/images/order_default_diagram.png";
                }
                var data = {
                    svgContent: svgContent,
                    svgContentJson: svgContentJson,
                    imageUrl: thumbnailUrl
                };
                // editCommon.log(data);
                if (callback) {
                    callback(data);
                }
            });
            // editCommon.putBase64Img(base64Img, ".png",function(res) {
            //     var thumbnailUrl="";
            //     if (res.code == 200) {
            //         thumbnailUrl = res.result;
            //         // appJson.thumbilUrl=base64Img;//解决字体在3d模型上不显示 ？新问题中文乱码
            //         // appJson.thumbilUrl = thumbnailUrl; //解决字体在3d模型上不显示 ？新问题中文乱码
            //     }
            //     var data={svgContent:svgContent,svgContentJson:svgContentJson,imageUrl:thumbnailUrl};
            //     // editCommon.log(data);
            //     if(callback){
            //         callback(data);                       
            //     }
            // });

        } else {
            var data = {
                svgContent: svgContent,
                svgContentJson: svgContentJson,
                imageUrl: base64Img
            };
            // editCommon.log(data);
            if (callback) {
                callback(data);
            }
        }
    }, "", true);
    // svgRenderCanvas(svgContent2,512, 512, function(base64Img) {
    //     editCommon.putBase64Img(base64Img, ".png", function(res) {
    //         var thumbnailUrl="";
    //         if (res.code == 200) {
    //             thumbnailUrl = res.result;

    //             // appJson.thumbilUrl=base64Img;//解决字体在3d模型上不显示 ？新问题中文乱码
    //             // appJson.thumbilUrl = thumbnailUrl; //解决字体在3d模型上不显示 ？新问题中文乱码
    //         }
    //         var data={svgContent:svgContent,svgContentJson:svgContentJson,imageUrl:thumbnailUrl};
    //         // editCommon.log(data);
    //         if(callback){
    //             callback(data);                       
    //         }
    //     });
    // });
    var data = {
        svgContent: svgContent,
        svgContentJson: svgContentJson
    };
    // editCommon.log(data);
    return data;
}

//将Svg 渲染成canvas
function svgRenderCanvas(svg, width, height, callback, outputFormat) {
    var c = document.createElement("canvas");
    width = width || 512;
    height = height || 512;
    c.width = width;
    c.height = height;
    canvg(c, svg, {
        log: true,
        // useCORS:true,
        // ignoreMouse: true,//参数设置，是否忽略鼠标  
        // ignoreAnimation: true,//是否忽略动画  
        renderCallback: function() {
            // var dataURL = c.toDataURL(outputFormat || 'image/png', 2.0);
            var dataURL = c.toDataURL();
            // window.open(dataURL);
            if (callback) {
                callback(dataURL);
            }
        }
    });
}
/**
 * [addOperateGroup description]
 * @param {[type]} target [description]  需要添加变换组件的对象
 * @param {[type]} type   [description]  是否需要显示变换组件  hide:隐藏   默认显示
 */
function addOperateGroup(target, type) {
    var svgObj = editSvgCore.svgObj,
        selectGroup = svgObj.selectGroup,
        locationMap = svgObj.locationMap;
    if (selectGroup) {
        selectGroup.each(function(item) {
            var name = item.data("name");
            if (name != "image" && name != "text") {
                item.hide();
            }
        });
    }
    var svg = svgObj.svg,
        svg_container = svgObj.svg_container,
        offset = svgObj.offset;
    var bbox = target.bbox();
    var l = bbox.x,
        t = bbox.y,
        w = bbox.width,
        h = bbox.height,
        bbox = {
            x: l,
            y: t,
            width: w,
            height: h
        };
    var matrix = new SVG.Matrix(target);
    var transformBox = editCommon.transformBox(l, t, w, h, matrix);
    //判断是否超出可编辑区
    determinePintInArea(transformBox);
    var operate_g = svg.group();
    var icon_group = [];
    icon_group.push(target);
    //svg viewbox 处理
    var ratio_temp = variablePool.viewbox_ratio;
    if (!ratio_temp) {
        var viewbox = svg.viewbox();
        ratio_temp = variablePool.viewbox_ratio = viewbox.width / variablePool.w_width;
    }
    var path = svg.path('M ' + transformBox.tl.x + ' ' + transformBox.tl.y + ' L ' + transformBox.tr.x + ' ' + transformBox.tr.y + ' ' + transformBox.br.x + ' ' + transformBox.br.y + ' ' + transformBox.bl.x + ' ' + transformBox.bl.y + ' Z');
    path.attr({
        "stroke": "#000",
        "fill": "none",
        "stroke-width": 1 * ratio_temp,
        "stroke-dasharray": 8 * ratio_temp + "," + ratio_temp * 3
    });
    path.data("name", "path");
    icon_group.push(path);

    // var circle = svg.circle(transformBox.r * 2);
    // circle.center(transformBox.center.x, transformBox.center.y);
    // circle.attr({
    //     "stroke": "#000",
    //     "stroke-width": 1*ratio_temp,
    //     "fill": "none"
    // });
    // circle.hide();
    // circle.data("name", "circle");
    // icon_group.push(circle);
    var icon_width = variablePool.icon_width = 30 * ratio_temp;

    var move_image = svg.image(editCommon.variablePool.iconPath + editCommon.variablePool.movePic, icon_width, icon_width);
    move_image.attr({
        "x": transformBox.tl.x - icon_width / 2,
        "y": transformBox.tl.y - icon_width / 2
    });
    move_image.data("name", "remove");
    icon_group.push(move_image);
    // var scale_image = svg.image(editCommon.variablePool.iconPath + editCommon.variablePool.scalePic, icon_width, icon_width);
    // scale_image.attr({
    //     "x": transformBox.tr.x - icon_width/2,
    //     "y": transformBox.tr.y - icon_width/2
    // });
    // scale_image.data("name", "scale");
    // icon_group.push(scale_image);

    var rotate_image = svg.image(editCommon.variablePool.iconPath + editCommon.variablePool.rotatePic, icon_width, icon_width);
    rotate_image.attr({
        "x": transformBox.br.x - icon_width / 2,
        "y": transformBox.br.y - icon_width / 2
    });
    rotate_image.data("name", "rotate");
    icon_group.push(rotate_image);

    // var remove_image = svg.image(editCommon.variablePool.iconPath + editCommon.variablePool.removePic, icon_width, icon_width);
    // remove_image.attr({
    //     "x": transformBox.tl.x - icon_width/2,
    //     "y": transformBox.tl.y - icon_width/2
    // });
    // remove_image.data("name", "remove");
    // icon_group.push(remove_image);

    if (type == "hide") {
        icon_group.forEach(function(item) {
            var name = item.data("name");
            if (name != "image" && name != "text") {
                item.hide();
            }
        });
    }
    operate_g
        .add(path)
        // .add(circle)
        .add(move_image)
        //.add(scale_image)
        //.add(remove_image)
        .add(rotate_image);

    svgObj.operate_g = operate_g;
    //区分每个item
    svgObj.operateG = svgObj.operateG || [];
    svgObj.operateG.push({
        key: target.attr("id"),
        g: operate_g
    });


    //暂时取消编辑功能
    if (!editSvgCore.editEnable) {
        icon_group = [];
    }
    //当前选中的控件
    svgObj.selectGroup = icon_group;
    // icon_group.push($textarea);
    var containerTouchMousedown = function(e) {
        //点击svg 所有区域操作方法
        if (editSvgCore.svgAreaAllCallback) {
            editSvgCore.svgAreaAllCallback();
        }
        if (variablePool.scaleSvgEditViewStatus) { //放大状态阻止默认
            e.preventDefault();
        }
        // hideMouseToolTips();
        var tagName = e.target.tagName;
        // editCommon.log("当前点击的元素名称为：" + tagName);
        var target = e.target.instance;
        if (target) {
            var name = target.data("name");
            if (name || tagName == "text" || tagName == "tspan") {
                // variablePool.currentObj=null;
                return;
            }
        }
        var group = svgObj.selectGroup;
        if (group) {
            group.forEach(function(item) {
                var name = item.data("name");
                if (name != "image" && name != "text") {
                    item.hide();
                } else {
                    if (name == "image") {
                        var type = item.data("type");
                        if (type == "userImage") {
                            if (editSvgCore.cancelSvgUserImageEditCallback) {
                                editSvgCore.cancelSvgUserImageEditCallback();
                            }
                        } else {
                            if (editSvgCore.cancelSvgMaterialEditCallback) {
                                editSvgCore.cancelSvgMaterialEditCallback();
                            }
                        }
                    } else if (name == "text") {
                        if (editSvgCore.cancelSvgTextEditCallback) {
                            editSvgCore.cancelSvgTextEditCallback();
                        }
                    }
                    item.data("prevObjId", null);
                }
            });
            // svgObj.selectGroup = null;
        }
        //需要操作的方法
        //点击svg 容器需要的回调方法
        if (editSvgCore.svgContainerClick) {
            editSvgCore.svgContainerClick();
        }
    };
    if (!variablePool.containerTouchMousedown) {
        if (variablePool.isPC) {
            svg_container.on("mousedown", containerTouchMousedown);
        } else {
            svg_container.on("touchstart", containerTouchMousedown);
        }
        variablePool.containerTouchMousedown = containerTouchMousedown;
    }
    icon_group.forEach(function(item) {
        var name = item.data("name");
        if (!name || name == "circle" || name == "path") {
            return false;
        }
        item.target = target;
        var touchMousedown = function(e) {
            e.preventDefault();
            e.stopPropagation();
            // $("body").css("overflow","hidden");
            var currentObj = this;
            variablePool.currentObj = currentObj;
            var name = currentObj.data("name");
            var selectGroup = svgObj.selectGroup;
            var tempTarget = currentObj.target;
            var prevObjId = "";
            var currentObjId = "";


            var curOperate = null;
            if (svgObj.operateG) {
                svgObj.operateG.forEach(function(item) {
                    if (item.key == tempTarget.attr("id")) {
                        curOperate = item.g;
                    }
                });
            }

            var selectGroup = curOperate.children(); // svgObj.selectGroup;
            icon_group = curOperate.children();


            // variablePool.prevClickTargetFlag = false;
            //若点击的为文字或者素材  设置这次的id
            if (name == "text" || name == "image") {
                // if (tempTarget) {
                //     // prevObjId = tempTarget.data("prevObjId");
                //     currentObjId = tempTarget.attr("id");
                //     tempTarget.data("prevObjId", currentObjId);
                // }
                // var gridObj=svgObj.gridObj;
                // if(gridObj){
                //     gridObj.show();
                // }
                if (selectGroup) {
                    selectGroup.each(function(item) {
                        var name = item.data("name");
                        if (name != "image" && name != "text") {
                            // item.hide();
                            item.target = tempTarget;
                        }
                    });
                }

                svgObj.operateG.forEach(function(item) {

                    item.g.children().forEach(function(child) {
                        child.hide();
                    })
                });

            }
            //如果两次id不为空并且相等则说明可以
            // if (prevObjId && currentObjId && prevObjId == currentObjId) {
            //     variablePool.prevClickTargetFlag = true;
            // }
            // bbox = tempTarget.tbox();
            variablePool.new_pos = null;
            var o_pos = {};
            if (!variablePool.isPC) {
                o_pos = variablePool.o_pos = variablePool.start_pos = editCommon.getTouchedPosition(e, offset, variablePool.viewbox_ratio);
            } else {
                o_pos = variablePool.o_pos = variablePool.start_pos = editCommon.getMousePosition(e, offset, variablePool.viewbox_ratio);
            }
            switch (name) {
                case "image":
                    var id = tempTarget.attr("id");
                    var type = tempTarget.data("type");
                    if (type == "userImage") {
                        var userImage = designModelMap.userImages[id];
                        if (userImage.locked) {
                            if (editSvgCore.svgUserImageEditCallback) {

                                delete userImage.imagebase64;
                                delete userImage.href;
                                editSvgCore.svgUserImageEditCallback(userImage);

                            }
                            return;
                        }
                    } else {
                        var material = designModelMap.materials[id];
                        if (editSvgCore.svgMaterialEditCallback) {
                            editSvgCore.svgMaterialEditCallback();
                        }
                    }
                    var gridObj = svgObj.gridObj;
                    if (gridObj) {
                        gridObj.show();
                    }
                    if (selectGroup) {
                        selectGroup.each(function(item) {
                            var name = item.data("name");
                            if (name != "image" && name != "text") {
                                item.hide();
                            }
                        });
                    }
                    if (icon_group) {
                        icon_group.forEach(function(item) {
                            var name = item.data("name");
                            if (name != "image" && name != "text" && name != "circle") {
                                var type = tempTarget.data("type");
                                // if(type=="userImage"&&name=="remove"){
                                //     item.hide()
                                // }else{
                                //     item.show();
                                // }
                                item.show();
                            }
                        });
                    }
                    svgObj.selectGroup = icon_group;
                    svgObj.operate_g = operate_g;
                    refreshComponent(tempTarget, icon_group);
                    break;
                case "text":
                    var id = tempTarget.attr("id");
                    var text = designModelMap.texts[id];
                    if (text.locked) {
                        return;
                    }
                    var gridObj = svgObj.gridObj;
                    if (gridObj) {
                        gridObj.show();
                    }
                    var attr = item.attr();
                    if (selectGroup) {
                        selectGroup.each(function(item) {
                            var name = item.data("name");
                            if (name != "image" && name != "text") {
                                item.hide();
                            }
                        });
                    }
                    if (icon_group) {
                        icon_group.forEach(function(item) {
                            var name = item.data("name");
                            if (name != "image" && name != "text" && name != "circle") {
                                item.show();
                            }
                        });
                    }
                    svgObj.selectGroup = icon_group;
                    refreshComponent(tempTarget, icon_group);
                    break;
                case "rotate":
                    //circle.show();
                    //variablePool.circleCurrent=circle;
                    break;
                case "remove":
                    var name = tempTarget.data("name");
                    var id = tempTarget.attr("id");
                    var type = tempTarget.data("type");

                    var curOperate = null;
                    svgObj.operateG.forEach(function(item) {
                        if (item.key == id) {
                            curOperate = item.g;
                        }
                    });

                    curOperate.remove();
                    //operate_g.remove();                            
                    tempTarget.remove();
                    if (editSvgCore.removeSvgObjCallback) {
                        editSvgCore.removeSvgObjCallback(name, type);
                    }
                    variablePool.currentObj = null;
                    if (name == "text") {
                        delete designModelMap.texts[id];
                    } else if (name == "image") {
                        if (type == "userImage") {
                            svgObj.userImages = null;
                            delete designModelMap.userImages[id];
                        } else {
                            delete designModelMap.materials[id];
                        }
                    }
                    break;
                default:
                    break;
            }
            variablePool.mouseStatus = true;
            var transform = tempTarget.transform();
            var touchmoveMouseMove = function(e) {
                // e.preventDefault();                        
                // e.stopPropagation();
                currentObj = variablePool.currentObj;
                if (!currentObj) return
                tempTarget = currentObj.target;
                if (tempTarget.attr("locked") == "true") return false;
                icon_group = svgObj.selectGroup;

                if (!variablePool.mouseStatus) {
                    return;
                }
                var new_pos = {};
                if (!variablePool.isPC) {
                    new_pos = variablePool.new_pos = editCommon.getTouchedPosition(e, offset, variablePool.viewbox_ratio);
                } else {
                    new_pos = variablePool.new_pos = editCommon.getMousePosition(e, offset, variablePool.viewbox_ratio);
                }
                o_pos = variablePool.o_pos;
                bbox = tempTarget.tbox();
                transform = tempTarget.transform();
                var dis_pos = {
                    // x: new_pos.x - o_pos.x,
                    // y: new_pos.y - o_pos.y
                };
                if (!variablePool.isPC) {
                    dis_pos = {
                        x: new_pos.point1.x - o_pos.point1.x,
                        y: new_pos.point1.y - o_pos.point1.y
                    };
                } else {
                    dis_pos = {
                        x: new_pos.x - o_pos.x,
                        y: new_pos.y - o_pos.y
                    };
                }
                name = currentObj.data("name");
                if (name) {
                    $("body").css("overflow", "hidden");
                }
                if (name == "text" || name == "image") {
                    // if (tempTarget) {
                    //     // prevObjId = tempTarget.data("prevObjId");
                    //     currentObjId = tempTarget.attr("id");
                    //     tempTarget.data("prevObjId", currentObjId);
                    // }
                    // var gridObj=svgObj.gridObj;
                    // if(gridObj){
                    //     gridObj.show();
                    // }
                    if (selectGroup) {
                        selectGroup.each(function(item) {
                            var name = item.data("name");
                            if (name != "image" && name != "text") {
                                // item.hide();
                                item.target = tempTarget;
                            }
                        });
                    }
                }
                switch (name) {
                    case "text":
                    case "image":
                    case "move":
                        var x = dis_pos.x * variablePool.viewbox_ratio + transform.x;
                        var y = dis_pos.y * variablePool.viewbox_ratio + transform.y;
                        if (variablePool.isPC) {
                            tempTarget.translate(x, y);
                        } else {
                            if (editCommon.isDragging(e)) {
                                tempTarget.translate(x, y);
                            } else if (editCommon.isPinching(e)) {
                                var oldScaleX = transform.scaleX;
                                var scaleX = Math.max(0, Math.min(oldScaleX * (editCommon.getZooms(new_pos) / editCommon.getZooms(o_pos)), 10));
                                tempTarget.scale(scaleX, scaleX);
                                var center = {
                                    x: bbox.cx,
                                    y: bbox.cy
                                };
                                var deg1 = editCommon.getAngles(o_pos);
                                var deg2 = editCommon.getAngles(new_pos);
                                var angle = deg2 - deg1;
                                angle = angle + transform.rotation;
                                tempTarget.rotate(angle);
                            }
                        }
                        refreshComponent(tempTarget, icon_group);
                        break;
                    case "scale":
                    case "rotate":

                        function scale() {
                            var center = {
                                x: bbox.cx,
                                y: bbox.cy
                            };
                            var o_posTemp = {},
                                new_posTemp = {};
                            var oldScaleX = transform.scaleX;
                            var scaleX = 1;
                            if (!variablePool.isPC) {
                                o_pos.point2 = center;
                                new_pos.point2 = center;
                                scaleX = Math.max(0, Math.min(oldScaleX * (editCommon.getZooms(new_pos) / editCommon.getZooms(o_pos)), 10));
                            } else {
                                o_posTemp = {
                                    point1: o_pos,
                                    point2: center
                                };
                                new_posTemp = {
                                    point1: new_pos,
                                    point2: center
                                };
                                scaleX = Math.max(0, Math.min(oldScaleX * (editCommon.getZooms(new_posTemp) / editCommon.getZooms(o_posTemp)), 10));
                            }
                            tempTarget.scale(scaleX, scaleX);
                            refreshComponent(tempTarget, icon_group);
                        }

                        function rotate() {

                            var center = {
                                x: bbox.cx,
                                y: bbox.cy
                            };
                            var y0 = o_pos.y - center.y,
                                x0 = o_pos.x - center.x,
                                y = new_pos.y - center.y,
                                x = new_pos.x - center.x;
                            if (!variablePool.isPC) {
                                y0 = o_pos.point1.y - center.y,
                                    x0 = o_pos.point1.x - center.x,
                                    y = new_pos.point1.y - center.y,
                                    x = new_pos.point1.x - center.x;
                            }
                            var deg = Math.atan2(y, x) - Math.atan2(y0, x0);
                            // var deg=Math.atan2(new_pos.y,new_pos.x)-Math.atan2(o_pos.y,o_pos.x);
                            // var angle=SVG.math.deg(deg);
                            var angle = 180 * deg / Math.PI;
                            // editCommon.log("当前弧度为angle=" + deg + "，当前角度为deg=" + angle);
                            angle = angle + transform.rotation;
                            tempTarget.rotate(angle);
                            refreshComponent(tempTarget, icon_group);
                        }
                        scale();
                        rotate();
                        break;
                    default:
                        break;
                }
                variablePool.o_pos = variablePool.new_pos;
            };
            if (!variablePool.touchmoveMouseMove) {
                if (variablePool.isPC) {
                    svg_container.on("mousemove", touchmoveMouseMove);
                } else {
                    svg_container.on("touchmove", touchmoveMouseMove);
                }
                variablePool.touchmoveMouseMove = touchmoveMouseMove;
            }

            var mouseupTouchend = function(e) {
                //点击svg 所有区域操作方法
                if (editSvgCore.svgAreaAllCallback) {
                    editSvgCore.svgAreaAllCallback();
                }
                if (!variablePool.scaleSvgEditViewStatus) {
                    $("body").css("overflow", "");
                }
                // e.preventDefault();
                // e.stopPropagation();
                // function mouseupFunc(e){
                var end_pos = variablePool.o_pos;
                var start_pos = variablePool.start_pos;
                var dis_pos = {
                    // x: end_pos.x - start_pos.x,
                    // y: end_pos.y - start_pos.y
                };
                if (!variablePool.isPC) {
                    dis_pos = {
                        x: end_pos.point1.x - start_pos.point1.x,
                        y: end_pos.point1.y - start_pos.point1.y
                    };
                } else {
                    dis_pos = {
                        x: end_pos.x - start_pos.x,
                        y: end_pos.y - start_pos.y
                    };
                }
                var gridObj = svgObj.gridObj;
                if (gridObj) {
                    gridObj.hide();
                }
                variablePool.mouseStatus = false;
                var currentObj = variablePool.currentObj;
                if (!currentObj) {
                    return;
                }
                var tempTarget = currentObj.target;
                if (!tempTarget) {
                    return;
                }
                if (e.target.nodeName == "image" && !$(e.target).attr("data-type")) {
                    return;
                }
                name = currentObj.data("name");
                switch (name) {
                    case "text":

                        if (dis_pos.x == 0 && dis_pos.y == 0) {
                            //可编辑需要回调的方法
                            if (editSvgCore.svgEditCallback) {
                                editSvgCore.svgEditCallback();
                            }
                            // 弹出svg 文字编辑窗口回调
                            if (editSvgCore.svgTextEditCallback) {
                                var id = tempTarget.attr("id");
                                var text = designModelMap.texts[id];
                                if (!text) {
                                    return;
                                }
                                text.id = id;
                                editSvgCore.svgTextEditCallback(text);
                            }
                        }
                        break;
                    case "rotate":
                        if (variablePool.circleCurrent) {
                            variablePool.circleCurrent.hide();
                        }
                        break;
                    case "image":
                        //只是点击操作 未移动
                        if (dis_pos.x < 1 && dis_pos.y < 1) {

                            // variablePool.new_pos=null;
                            //可编辑需要回调的方法
                            if (editSvgCore.svgEditCallback) {
                                editSvgCore.svgEditCallback();
                            }
                            var type = tempTarget.data("type");
                            if (type == "userImage") {
                                //用户图片编辑
                                if (editSvgCore.svgUserImageEditCallback) {
                                    var id = tempTarget.attr("id");
                                    var userImage = designModelMap.userImages[id];
                                    userImage.id = id;
                                    delete userImage.imagebase64;
                                    delete userImage.href;
                                    editSvgCore.svgUserImageEditCallback(userImage);
                                }
                            } else {
                                //素材图片编辑
                                if (editSvgCore.svgMaterialEditCallback) {
                                    editSvgCore.svgMaterialEditCallback();
                                }
                            }
                            break;
                        }
                        // var type = tempTarget.data("type");
                        // //如果为用户图片则显示操作工具条
                        // if (type == "userImage") {
                        //     // showMouseToolTips(e);
                        // }
                        break;
                    default:
                        break;

                }
                // item.onmousemove=null;
                // if(variablePool.isPC){
                //     document.onmousemove = null;
                //     document.onmouseup = null;
                // }else{
                //     svg_container.off("mousemove");
                //     svg_container.off("mouseup");
                // }
                // item.off();
                // document.removeEventListener("mousemove",mousemoveFunc,false);
                return true;
            };
            if (!variablePool.mouseupTouchend) {
                if (variablePool.isPC) {
                    svg_container.on("mouseup", mouseupTouchend);
                } else {
                    svg_container.on("touchend", mouseupTouchend);
                }

                variablePool.mouseupTouchend = mouseupTouchend;
            }
        };
        if (variablePool.isPC) {
            item.on("mousedown", touchMousedown);
        } else {
            item.on("touchstart", touchMousedown);
        }
    });
}
/**
 * mask层添加回调事件
 */
function addMaskOperate(target) {

    target.on("touchstart", function() {
        if (editSvgCore.touchMaskCallback) {
            editSvgCore.touchMaskCallback();
        }

    });
}

function loadSvgMaskImageByBase64(options) {
    var svgObj = editSvgCore.svgObj,
        // slitTypeMap = svgObj.slitTypeMap ? svgObj.slitTypeMap : {},
        svg = svgObj.svg;
    var params = options.params,
        data = options.data,
        target = options.target,
        callback = options.callback,
        imageObj = options.imageObj,
        realImageUrl = params.realImageUrl,
        // type=options.type,//"mask" 有type
        width = params.width,
        height = params.height,
        // picWidth = slitTypeMap.picWidth,
        // picHeight = slitTypeMap.picHeight,
        x = params.x || 0,
        y = params.y || 0,
        isExsists = false;
    // var ratio = 1;
    // ratio = Math.min(picHeight * ratio / height, picWidth * ratio / width);
    //重新设置图片高宽
    // width = width * ratio;
    // height = height * ratio;
    // xaxis = picWidth / 2 - width / 2 + xaxis;
    // yaxis = picHeight / 2 - height / 2 + yaxis;
    if (data.imagebase64) {
        var svg_tmp_image = imageObj;
        if (svg_tmp_image) {
            svg_tmp_image.load(params.imagebase64);
            // that.refreshComponent(svg_tmp_image,svgObj.selectGroup);
            isExsists = true;
        } else {
            svg_tmp_image = svg.image(params.imagebase64, width, height);
        }
        // if(type=="mask"){//如果图片为蒙版 则重设置宽高

        // }
        if (data.matrix) {
            svg_tmp_image.matrix(editCommon.changeMatrix(data.matrix));
        }
        // svg_tmp_image.data("href",realImageUrl);
        // svg_tmp_image.attr({x:x,y:y});
        if (!isExsists) {
            target.add(svg_tmp_image);
            if (params.isActive) {
                svg_tmp_image.data("name", "image");
                addOperateGroup(svg_tmp_image, "hide");
            }
            addMaskOperate(svg_tmp_image);
        }
        if (callback) {
            callback(svg_tmp_image);
        }
    } else {
        editCommon.convertImgToBase64(editCommon.loadImgUrl(editCommon.imgService.imgServer, params.imageUrl, {
            width: variablePool.w_width
        }), function(base64Img) {
            // var base64Img=params.imageUrl;
            data.imagebase64 = base64Img;
            var svg_tmp_image = imageObj;
            if (svg_tmp_image) {
                svg_tmp_image.load(base64Img);
                // refreshComponent(svg_tmp_image,svgObj.selectGroup);
                isExsists = true;
            } else {
                svg_tmp_image = svg.image(base64Img, width, height);
            }
            // svg_tmp_image.attr({x:x,y:y});
            if (data.matrix) {
                svg_tmp_image.matrix(editCommon.changeMatrix(data.matrix));
            }
            // svg_tmp_image.data("href",realImageUrl);
            if (!isExsists) {
                target.add(svg_tmp_image);
                if (params.isActive) {
                    svg_tmp_image.data("name", "image");
                    addOperateGroup(svg_tmp_image, "hide");

                }
                addMaskOperate(svg_tmp_image);
            }
            if (callback) {
                callback(svg_tmp_image);
            }
        });
    }
}

function createRect(maskRect) {
    var svgObj = editSvgCore.svgObj;

    var width = maskRect.width;
    var height = maskRect.height;
    var matrix = maskRect.matrix;
    var rect = svgObj.svg.rect(width, height).fill("#ffffff");
    rect.attr("transform", matrix);
    svgObj.mask2.add(rect);
    setTimeout(function() {
        svgObj.texts_g.maskWith(svgObj.mask2);
        svgObj.texts_g.attr("mask", "url(#" + svgObj.mask2.attr("id") + ")");
    }, 0);


}

// 加载蒙版图片
function loadMaskImage(maskImage, callback) {
    var svgObj = editSvgCore.svgObj,
        svg = svgObj.svg,
        slitTypeMap = svgObj.slitTypeMap ? svgObj.slitTypeMap : {},
        mask = svgObj.mask,
        face_g = svgObj.face_g;
    if (maskImage && maskImage.url) {
        var imageUrl = maskImage.url;
        var imgPath = editCommon.loadImgUrl(editCommon.imgService.imgServer, imageUrl, {
            width: variablePool.w_width
        });
        // var imgPath = editCommon.imgService.imgServer + dataImgPath;
        loadSvgMaskImageByBase64({
            params: {
                width: maskImage.width,
                height: maskImage.height,
                x: maskImage.maskX,
                y: maskImage.maskY,
                imagebase64: maskImage.imagebase64,
                imageUrl: imgPath,
                realImageUrl: imageUrl,
                isActive: false
            },
            data: maskImage,
            target: mask,
            callback: function(target) {
                // target.data("type","userImage");
                var id = target.attr("id");
                face_g.maskWith(mask);
                face_g.attr("mask", "url(#" + mask.attr("id") + ")");
                var transform = target.transform();
                var matrix = new SVG.Matrix(target);
                maskImage.matrix = {
                    "translateX": transform.x,
                    "translateY": transform.y,
                    "scale": transform.scaleX,
                    "rotate": transform.rotation
                };
                maskImage.matrixString = matrix.toString();
                designModelMap.mask[id] = maskImage;
                svgObj.maskImage = target;
                //蒙版图片加载完毕展示
                target.loaded(function() {
                    //创建网格 
                    var bbox = target.bbox();
                    var l = bbox.x,
                        t = bbox.y,
                        w = bbox.width,
                        h = bbox.height,
                        unit_x = w / 3,
                        unit_y = h / 3;
                    // var matrix = new SVG.Matrix(target);
                    var transformBox = editCommon.transformBox(l, t, w, h, matrix);
                    var ratio_temp = variablePool.viewbox_ratio;
                    if (!ratio_temp) {
                        var viewbox = svg.viewbox();
                        ratio_temp = variablePool.viewbox_ratio = viewbox.width / variablePool.w_width;
                    }
                    // var gridGroup=svg.group();
                    var gridPath = "";
                    var pathLineAttr = {
                        // "stroke": "#f2f2f2",
                        "stroke": "#ccc",
                        "fill": "none",
                        "pointer-events": "none",
                        "stroke-width": 1,
                        "stroke-dasharray": "10,5" //8*ratio_temp+","+ratio_temp*3
                    };
                    for (var i = 1; i < 3; i++) {
                        var v_path_line = ' M ' + transformBox.tl.x + ' ' + (transformBox.tl.y + unit_y * i) + ' L ' + (transformBox.tl.x + unit_x * 3) + ' ' + (transformBox.tl.y + unit_y * i) + " Z";
                        var h_path_line = ' M ' + (transformBox.tl.x + unit_x * i) + ' ' + transformBox.tl.y + ' L ' + (transformBox.tl.x + unit_x * i) + ' ' + (transformBox.tl.y + unit_y * 3) + " Z";
                        gridPath += v_path_line + h_path_line;
                    }
                    var pathLine = 'M ' + transformBox.tl.x + ' ' + transformBox.tl.y +
                        ' L ' + transformBox.tr.x + ' ' + transformBox.tr.y +
                        ' ' + transformBox.br.x + ' ' + transformBox.br.y +
                        ' ' + transformBox.bl.x + ' ' + transformBox.bl.y + ' Z ' + gridPath + ' Z';
                    var path = svg.path(pathLine);
                    path.attr(pathLineAttr);
                    path.data("name", "path");
                    path.hide();
                    svgObj.gridObj = path;
                    //可编辑区动画   true为展示  false为不展示  默认不展示
                    if (editSvgCore.enableAnimateRect) {
                        editSvgCore.animateRectType = editSvgCore.animateRectType || 1;
                        var animateOb = null;
                        var transform = target.transform();
                        if (editSvgCore.animateRectType == 2) {
                            editSvgCore.animateRectColor = editSvgCore.animateRectColor || "rgba(255,0,0,.5)";
                            animateObj = svg.rect(w, h).fill(editSvgCore.animateRectColor).move(transform.x, transform.y).attr({
                                "pointer-events": "none"
                            });
                            animateObj.animate({
                                opacity: 0
                            }).loop();
                        } else {
                            editSvgCore.animateRectImage = editSvgCore.animateRectImage || "";
                            var width = 150 * variablePool.viewbox_ratio,
                                height = 150 * variablePool.viewbox_ratio;
                            var x = transform.x + (w - width) / 2,
                                y = transform.y + (h - height) / 2;
                            animateObj = svg.image(editCommon.loadImgUrl(editCommon.imgService.imgServer, editSvgCore.animateRectImage), width, height)
                                .move(x, y).attr({
                                    "pointer-events": "none"
                                });
                            // animateObj.animate({opacity:0}).loop();
                        }
                        animateObj.hide();
                        svgObj.animateObj = animateObj;
                    }
                });

                if (callback) {
                    callback();
                }
            }
        });
    } else {
        if (callback) {
            callback();
        }
    }
}

// 加载可点击蒙版图片
function loadMaskUserImage(maskImage, callback) {
    var svgObj = editSvgCore.svgObj,
        svg = svgObj.svg,
        slitTypeMap = svgObj.slitTypeMap ? svgObj.slitTypeMap : {},
        maskuserImage_g = svgObj.maskuserImage_g,
        face_g = svgObj.face_g;
    if (maskImage && maskImage.url) {
        var imageUrl = maskImage.url;
        var imgPath = editCommon.loadImgUrl(editCommon.imgService.imgServer, imageUrl, {
            width: variablePool.w_width
        });
        // var imgPath = editCommon.imgService.imgServer + dataImgPath;
        loadSvgMaskImageByBase64({
            params: {
                width: maskImage.width,
                height: maskImage.height,
                x: maskImage.maskX,
                y: maskImage.maskY,
                imagebase64: maskImage.imagebase64,
                imageUrl: imgPath,
                realImageUrl: imageUrl,
                isActive: false
            },
            data: maskImage,
            target: maskuserImage_g,
            callback: function(target) {

                target.style('opacity', '0')
                if (callback) {
                    callback();
                }
            }
        });
    }
}

//停止编辑区提示动画        
function stopEditRectAnimate() {
    var svgObj = editSvgCore.svgObj;
    if (svgObj.animateObj) {
        svgObj.animateObj.hide();
        if (svgObj.animateObj.stop) {
            svgObj.animateObj.stop();
        }
    }
}
//开始显示编辑区提示动画        
function startEditRectAnimate() {
    var svgObj = editSvgCore.svgObj;
    if (svgObj.animateObj) {
        svgObj.animateObj.show();
        if (svgObj.animateObj.start) {
            svgObj.animateObj.start();
        }
    }
}

/**
 * 加载用户图片
 * @param {*} index 索引
 * @param {*} userImages  用户图片列表
 * @param {*} callback   回调
 */
function loadUserImages(index, userImages, callback) {
    var svgObj = editSvgCore.svgObj,
        userImage_g = svgObj.userImage_g,
        userImageObj = svgObj.userImages,
        len = userImages ? userImages.length : 0;
    if (index >= len) {
        if (callback) {
            callback();
        }
        return;
    }
    var obj = userImages[index];
    if (!obj) {
        if (callback) {
            callback();
        }
        return;
    }
    var imageUrl = obj.url;
    // var originalImageUrl = editCommon.loadImgUrl(editCommon.imgService.imgServer, imageUrl);
    // var thumbilUrl=editCommon.loadImgUrl(editCommon.imgService.imgServer,imageUrl,editCommon.imgService.qnProduct300);
    var imgPath = editCommon.loadImgUrl(editCommon.imgService.imgServer, imageUrl, {
        width: variablePool.w_width * 2
    });
    loadSvgImageByBase64({
        params: {
            width: obj.width,
            height: obj.height,
            x: obj.maskX,
            y: obj.maskY,
            imagebase64: obj.imagebase64,
            imageUrl: imgPath,
            realImageUrl: imageUrl,
            isActive: true
        },
        imageObj: userImageObj,
        data: obj,
        target: userImage_g,
        callback: function(target) {
            target.data("type", "userImage");
            var id = target.attr("id");
            var transform = target.transform();
            var matrix = new SVG.Matrix(target);
            obj.matrix = {
                "translateX": transform.x,
                "translateY": transform.y,
                "scale": transform.scaleX,
                "rotate": transform.rotation
            };
            obj.matrixString = matrix.toString();
            obj.realImageUrl = imageUrl;
            designModelMap.userImages[id] = obj;
            svgObj.userImages = target;
            index++;
            loadUserImages(index, userImages, callback);
        }
    });
}
/**
 * 添加素材
 * [addMaterialToSvg description]
 * @param {[type]} item [description]  素材对象
 */
function addMaterialToSvg(item, callback) {
    var svgObj = editSvgCore.svgObj,
        svg = svgObj.svg,
        materials_g = svgObj.materials_g;
    var width = item.width,
        height = item.height || item.high,
        dpi = item.imgDpi || 200,
        imageUrl = item.uri || item.path;
    // var originalImageUrl = editCommon.loadImgUrl(editCommon.imgService.imgServer, imageUrl);
    // var thumbilUrl=editCommon.loadImgUrl(editCommon.imgService.imgServer,imageUrl,editCommon.imgService.qnProduct300);
    // var dataImgPath = editCommon.loadImgUrl("", imageUrl, editCommon.imgService.qnProductDync.substitute({ width: "", height: "", quality: "/q/30" }));
    var imgPath = editCommon.loadImgUrl(editCommon.imgService.imgServer, imageUrl, {
        width: 380
    });
    // var imgPath = editCommon.imgService.imgServer + dataImgPath;
    var userImageData = {
        width: width,
        height: height,
        url: imageUrl,
        // remoteOriginalImageUrl: imageUrl
    };
    loadSvgImageByBase64({
        params: {
            width: width,
            height: height,
            imagebase64: item.imagebase64,
            imageUrl: imgPath,
            isActive: true
        },
        // imageObj:userImage,
        data: userImageData,
        target: materials_g,
        callback: function(target) {
            // target.data("type","userImage");
            var id = target.attr("id");
            // rule = 4;
            // // var rule = productTemplate.templateBo.rule;//规则
            // var ratio = 1;
            // // var printDpi=productTemplate.printDpi;//打印dpi

            // // var w = pw, h = ph;
            // // 最大高度
            // // var maxHeight = height / printDpi * 2.54 * dpi / printDpi / 2.54 * dpi; // in pixel
            // // 最大宽度
            // // var maxWidth = width / printDpi * 2.54 * dpi / printDpi / 2.54 * dpi; // in pixel
            // var viewbox = svg.viewbox();
            // if (rule == 4) {
            //     // ratio = Math.max(viewbox.height * ratio / height, viewbox.width * ratio / width);
            //     ratio = Math.min(viewbox.height * ratio / height, viewbox.width * ratio / width);
            // } else {
            //     // ratio = Math.min(maxHeight / height, viewbox.height * ratio / height, viewbox.width * ratio / width);
            // }
            var maskImage = variablePool.maskImage;
            var ratio = 1,
                x = 0,
                y = 0;
            if (maskImage) {
                ratio = Math.min(maskImage.height * ratio / height, maskImage.width * ratio / width);
                var x = maskImage.width / 2 - width / 2 + parseFloat(maskImage.maskX),
                    y = maskImage.height / 2 - height / 2 + parseFloat(maskImage.maskY);
            } else {
                ratio = Math.min(variablePool.w_height * ratio / height, variablePool.w_width * ratio / width);
                x = variablePool.w_width / 2 - width / 2,
                    y = variablePool.w_height / 2 - height / 2;
            }
            // width = width * ratio;
            // height = height * ratio;
            //重新设置图片高宽
            target.attr({
                "width": width / 2,
                "height": height / 2
            });
            // var x = viewbox.width / 2 - width / 2,
            //     y = viewbox.height / 2 - height / 2;
            // target.translate(x,y);
            // var scale=Math.max(viewbox.width/width,viewbox.height/height);
            var matrix = new SVG.Matrix;
            matrix = matrix.translate(x + Math.random(1) * 100, y + Math.random(1) * 100);
            target.matrix(matrix);
            target.scale(ratio);
            refreshComponent(target, svgObj.selectGroup);
            var transform = target.transform();
            userImageData.matrix = {
                "rotate": transform.rotation,
                "scale": transform.scaleX,
                "translateX": transform.x,
                "translateY": transform.y
            };
            userImageData.matrixString = new SVG.Matrix(target).toString();
            userImageData.realImageUrl = imageUrl;
            // svgObj.userImage=target;
            designModelMap.materials[id] = userImageData;
            removeOverMaxMaterial(svgObj, 20);
            if (callback) {
                callback();
            }
        }
    });
}


//加载编辑区素材图片
function loadMaterials(index, materials, callback) {
    var svgObj = editSvgCore.svgObj,
        materials_g = svgObj.materials_g,
        len = materials ? materials.length : 0;
    if (index >= len) {
        if (callback) {
            callback();
        }
        return;
    }
    var obj = materials[index];
    obj.isDefaultMaterial = true;
    if (!obj) {
        if (callback) {
            callback();
        }
        return;
    }
    var imageUrl = obj.url;
    // var originalImageUrl = editCommon.loadImgUrl(editCommon.imgService.imgServer, imageUrl);
    // var thumbilUrl=editCommon.loadImgUrl(editCommon.imgService.imgServer,imageUrl,editCommon.imgService.qnProduct300);
    var imgPath = editCommon.loadImgUrl(editCommon.imgService.imgServer, imageUrl, {
        width: variablePool.w_width * 2
    });
    loadSvgImageByBase64({
        params: {
            width: obj.width,
            height: obj.height,
            x: obj.maskX,
            y: obj.maskY,
            imagebase64: obj.imagebase64,
            imageUrl: imgPath,
            realImageUrl: imageUrl,
            isActive: true
        },
        data: obj,
        target: materials_g,
        callback: function(target) {
            var id = target.attr("id");
            var transform = target.transform();
            var matrix = new SVG.Matrix(target);
            obj.matrix = {
                "translateX": transform.x,
                "translateY": transform.y,
                "scale": transform.scaleX,
                "rotate": transform.rotation
            };
            obj.matrixString = matrix.toString();
            designModelMap.materials[id] = obj;
            index++;
            loadMaterials(index, materials, callback);
        }
    });
}
//加载编辑区背景图片
function loadBackgroundImages(index, backgroundImages, callback) {
    var svgObj = editSvgCore.svgObj,
        background_g = svgObj.background_g,
        backgroundImageObj = svgObj.backgroundImageObj,
        len = backgroundImages ? backgroundImages.length : 0;
    if (index >= len) {
        if (callback) {
            callback();
        }
        return;
    }
    var obj = backgroundImages[index];
    if (!obj) {
        if (callback) {
            callback();
        }
        return;
    }
    var imageUrl = obj.url;
    // var originalImageUrl = editCommon.loadImgUrl(editCommon.imgService.imgServer, imageUrl);
    // var thumbilUrl=editCommon.loadImgUrl(editCommon.imgService.imgServer,imageUrl,editCommon.imgService.qnProduct300);
    var imgPath = editCommon.loadImgUrl(editCommon.imgService.imgServer, imageUrl, {
        width: variablePool.w_width * 2
    });
    loadSvgImageByBase64({
        params: {
            width: obj.width,
            height: obj.height,
            x: obj.maskX,
            y: obj.maskY,
            imagebase64: obj.imagebase64,
            imageUrl: imgPath,
            realImageUrl: imageUrl,
            isActive: true
        },
        imageObj: backgroundImageObj,
        data: obj,
        target: background_g,
        callback: function(target) {
            var id = target.attr("id");
            var transform = target.transform();
            var matrix = new SVG.Matrix(target);
            obj.matrix = {
                "translateX": transform.x,
                "translateY": transform.y,
                "scale": transform.scaleX,
                "rotate": transform.rotation
            };
            obj.matrixString = matrix.toString();
            designModelMap.backgroundImages[id] = obj;
            svgObj.backgroundImageObj = target;
            index++;
            loadBackgroundImages(index, backgroundImages, callback);
        }
    });
}

function initSvg(options, data, callback) {
    variablePool.containerTouchMousedown = null;
    variablePool.touchmoveMouseMove = null;
    variablePool.mouseupTouchend = null;
    if (typeof(data) == "string") {
        data = JSON.parse(data);
    }

    if (typeof(data.modelJson) == "string") {
        data = JSON.parse(data.modelJson);
    }

    //重置裁片设计的相关数据模型
    designModelMap = {
        back: {}, //基础数据
        backgroundImage: {}, //编辑区背景图片层
        userImages: {}, //用户图片
        materials: {}, //素材
        mask: {}, //蒙版
        texts: {} //文字
    };
    var that = this;
    data = $.extend(true, {}, data);
    var svgModelImgVo = data.svgModelImgVo || [];
    var svgImgVo = data.svgImgVo || [];
    var svgTextVo = data.svgTextVo || [];
    var backImage = null,
        maskImage = null,
        userImages = [], //编辑区用户图片层
        backgroundImages = [], //编辑区背景层
        decoratorImage = null;
    materialImages = [],
        texts = svgTextVo,
        textLen = texts ? texts.length : 0;

    var svgObj = {};
    editSvgCore.svgObj = svgObj;

    if (!options) {
        options = {};
    }
    var containerId = options.containerId;
    if (!containerId) {
        containerId = "svg_container_wrap";
    }
    if ($("#" + containerId).length < 1) {
        editCommon.log("svg内容展示容器id不存在，请创建！", "error");
        return;
    }
    var svg_container = SVG(containerId);
    svg_container.attr({
        id: "svg_container_inner"
    })
    svgObj.svg_container = svg_container;
    var w_width = variablePool.w_width = $(window).width(),
        w_height = variablePool.w_height = $(window).height();
    if (options.containerWidth) {
        w_width = variablePool.w_width = options.containerWidth;
    }
    if (options.containerHeight) {
        w_height = variablePool.w_height = options.containerHeight;
    }

    var svg = svg_container.nested();
    svg.attr({
        id: "svg-container"
    })
    svgObj.svg = svg;
    // function loadSvgContainer(data) {

    var xaxis = 0,
        yaxis = 0;
    svg_height = backImage.height,
        svg_width = backImage.width;
    var ratio = w_width / backImage.width;
    var see_height = 0;

    svg_width = svg_width * ratio;
    svg_height = svg_height * ratio;
    svg_container.size(w_width, svg_height);
    variablePool.svg_container_height = svg_height;
    // svg_container.viewbox({ x: 0, y: 0, width:1000, height: 1250 });
    // svg_container.attr({preserveAspectRatio:"xMidYMin meet"});
    // xaxis = xaxis * ratio * 2;
    // yaxis = yaxis * ratio * 2;
    // var offset = { x: (w_width - svg_width) / 2, y: (w_height - svg_height) / 2 };                
    var offset = {
        x: 0,
        y: 0
    };
    // data.editorRegionHeight = 512;
    // data.editorRegionWidth = 512;
    svg.viewbox({
        x: 0,
        y: 0,
        width: backImage.width,
        height: backImage.height
    });
    // svg.viewbox({ x: 0, y: 0, width: data.editorRegionWidth, height: data.editorRegionHeight });
    svg.size(svg_width, svg_height);
    svg.attr(offset);
    offset.ratio = 1;
    svgObj.offset = offset;
    variablePool.svgOffset = offset;
    variablePool.svgBox = {
        width: svg_width,
        height: svg_height
    };
    var viewbox = svg.viewbox();
    variablePool.viewbox_ratio = variablePool.viewbox_ratio_before = viewbox.width / variablePool.w_width;
    // }

    // loadSvgContainer(data);
    //窗口变化重新规划
    // window.dataTemp={editorRegionWidth:data.editorRegionWidth,editorRegionHeight:data.editorRegionHeight};
    // window.onresize=function(){
    //     var dataTemp=window.dataTemp;
    //     loadSvgContainer(dataTemp);
    // };
    // 画布层
    var canvas_g = svg.group();
    svgObj.canvas_g = canvas_g;
    canvas_g.attr({
        id: "svg_edit_canvas"
    });

    //框架层
    var frame_g = svg.group();
    svgObj.frame_g = frame_g;
    frame_g.attr({
        id: "svg_frame"
    });
    var mask = svg.mask();
    mask.attr({
        id: "svg_frame_mask"
    });
    svgObj.mask = mask;

    var face_g = svg.group();
    svgObj.face_g = face_g;
    var materials_g = svg.group(),
        texts_g = svg.group(),
        background_g = svg.group(),
        maskuserImage_g = svg.group(),
        userImage_g = svg.group();
}

export default editSvgCore;